Java Coding Conventions

It is expected that the information presented here will provide the reader with ideas and guidelines pertaining to coding conventions in Java. The areas to be covered are naming conventions, source code structure and documenting code.

Purpose

Coding conventions and code documentation is necessary because most of a program’s life cycle is spent in maintenance and is rarely maintain by the original author. Conventions aid in the readability and understandability of source code by persons who know, understand and follow the given convention.

Naming Conventions

File Suffixes

Java source code files have a suffix of .java.
Java class files have a suffix of .class

Common File Names

Makefile – the command script file to build an application.
README – the file that summarizes the contents of a particular directory.

Packages

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. Subsequent components of the package name should include the organization name (gru) and then whatever other subdivisions that are appropriate.

For example,
com.gru.isd.utils.strings

Classes

Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML). When acronyms are used they can be all upper case letters. The .java filename and the generated .class filename must and will be the same as the class name coded in the source file; it is case sensitive.

For example,
class Raster;
class ImageSprite;

Interfaces

Interface names should be capitalized like class names. When the interface is like an abstract superclass then use a noun. When the interface provides additional information about the class that it implements use an adjective (eg. Runnable).

For example,
interface RasterDelegate;
interface Storing;

Methods

Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.

For example,
run();
runFast();
getBackground();

Variables

Variables are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. The use of the $ character in a variable should be avoided altogether; it is used by code generation tools. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.

For example,
int i;
char c;
float myWidth;

Constants

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

For example,
static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;

Parameters

Use the same convention as variable names. They should be meaningful and consistenly used across multiple methods in a class.

Source Code Structure

Source File Overall Structure

A source file consists of sections that should be separated by blank lines and an optional comment identifying each section. Files longer than 2000 lines are cumbersome and should be avoided. In general, if your class is over 2000 lines and/or any method is over 100 lines then there is probably a problem with your design.

Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file. Private classes are listed next in alphabetical order.

Java source files have the following ordering of sections:
Beginning comments
Package and Import statements
Class or Interface declarations

Beginning Comments

All source files should begin with a c-style comment that lists the class name, version information (original author, version number and date, revision author, version number and date) and copyright notice. The <> indicates that the information specified should be place at that spot.

/*
 * <Classname>
 * 
 * Version Information:
 * Author              Version    Date
 * <original author>   <version#> <dd mmm yyyy>
 *  <comment about version>
 * <revision author>   <version#> <dd mmm yyyy>
 *  <comment about version>
 * …
 *
 * <Copyright notice>
 */

Package and Import statements

The first non-comment line of most Java source files is a package statement. After that, import statements can follow. For example:

package java.awt;

import java.awt.peer.CanvasPeer;

Note: The first component of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. See Packages Naming Convention.

Class or Interface declarations

This section consists of the following subsections:
Class/Interface documentation comments
Class or Interface statement
Class/Interface implementation comments
Class (static) variables
Instance variables
Constructors
Methods

The public class/interface should be listed first and then any private classes next in alphabetical order.

Class/Interface documentation comments

Doc comments describe Java classes, interfaces, constructors, methods, and fields. See the section on documentation comments.


Class or Interface Statement

The public class/interface declarations should be listed first and then any private classes next in alphabetical order. The actual individual class or interface statements have no special coding convention.

Class/Interface implementation comments

This comment should contain any class-wide or interface-wide information that wasn't appropriate for the class/interface documentation comment. See the section on implementation comments.

Class (static) variables

First the public class variables, then the protected, then package level (no access modifier), and then the private.

Instance variables

First public, then protected, then package level (no access modifier), and then private.

Constructors

List the default constructor first and then any alternate constructors.

Methods

These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.

Source Statement Structure

Statements per Line

One declaration per line is recommended since it encourages commenting. In other words,

int level; // indentation level
int size; // size of table

is preferred over

int level, size;

Do not put different types on the same line. Example: int foo, fooarray[]; //WRONG!

Each line should contain at most one statement. Example:

argv++;       // Correct
argc--;       // Correct  
argv++; argc--;       // AVOID!

Line Lengths

Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools. Examples for use in documentation should have a shorter line length-generally no more than 70 characters.

Indentation and White Space

Use a readable indentation for each level, either tabs or spaces.

Blank spaces should be used in the following circumstances:

A keyword followed by a parenthesis should be separated by a space.

Example:
while (true)
{
...
}

Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls.

Example: myMethod(int i, int j);

A blank space should appear after commas in argument lists.

All binary operators except . should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands.

Example:
a += c + d;
a = (a + b) / (c * d);

while (d++ = s++)
{
n++;
}

printSize("size is " + foo + "\n");

The expressions in a for statement should be separated by blank spaces.

Example:
for (expr1; expr2; expr3)

Casts should be followed by a blank space.

Examples:
myMethod((byte) aNum, (Object) x);
myMethod((int) (cp + 5), ((int) (i + 3)) + 1);

Line Wrapping

When an expression will not fit on a single line, break it according to these general principles:

Here are some examples of breaking method calls:

someMethod(longExpression1, longExpression2, longExpression3, 
           longExpression4, longExpression5);
var = someMethod1(longExpression1,
      someMethod2(longExpression2,
                  longExpression3));

Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.

longName1 = longName2 * (longName3 + longName4 – longName5)
            + 4 * longName6; // PREFER
longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longName6; // AVOID

Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.

//CONVENTIONAL INDENTATION
someMethod(int anArg, Object anotherArg, String yetAnotherArg,
           Object andStillAnother)
{
    ...
}

//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
private static synchronized horkingLongMethodName(int anArg,
        Object anotherArg, String yetAnotherArg,
        Object andStillAnother)
{
    ...
}

Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:

//DON'T USE THIS INDENTATION
if ((condition1 && condition2)
    || (condition3 && condition4)
    ||!(condition5 && condition6)) { //BAD WRAPS
    doSomethingAboutIt();            //MAKE THIS LINE EASY TO MISS
} 

//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6))
{
    doSomethingAboutIt();
}

//OR USE THIS
if ((condition1 && condition2) || (condition3 && condition4)
        ||!(condition5 && condition6))
{
    doSomethingAboutIt();
} 

Here are three acceptable ways to format ternary expressions:

alpha = (aLongBooleanExpression) ? beta : gamma;
alpha = (aLongBooleanExpression) ? beta : gamma;
alpha = (aLongBooleanExpression) ? beta : gamma;

Variable Initialization and Placement

Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.

Put declarations only at the beginning of blocks that encompasses the scope in which the variable will be used. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

void myMethod()
{
    int int1 = 0;      // beginning of method block
    if (condition)
    {
     int int2 = 0;     // beginning of "if" block
     ...
    }
}

As an alternative you could simple declare variables at the beginning of the class or method block.

The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement:
for (int i = 0; i < maxLoops; i++) { ... }

Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

int count;
...
myMethod()
{
 if (condition)
 {
  int count = 0;     // AVOID!
  ...
 }
...
}

Class, Interface and Method Declarations

No space between a method name and the parenthesis "(" starting its parameter list.

Open brace "{" and Closing brace "}" starts a line by itself indented to match its corresponding declaration statement, except when it is a null statement the "}" should appear immediately after the "{". A blank line separates methods.

class Sample extends Object
{
 int ivar1;
 int ivar2;

 Sample(int i, int j)
 {
  ivar1 = i;
  ivar2 = j;
 }

 int emptyMethod()
 {
 }

 ...

}

Compound Statements

Compound statements are statements that contain lists of statements enclosed in braces "{ statements }".

Indentation should follow standard indicated above.

Open brace "{" and Closing brace "}" starts a line by itself indented to match its corresponding declaration statement.

Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.

return Statements

A return statement with a value should not use parentheses unless they make the return value more obvious in some way.

Example:
return;
return myDisk.size();
return (size ? size : defaultSize);


if, if-else, if else-if else Statements

The if-else class of statements should have the following form:

if (condition)
{
 statements;
}

if (condition)
{
 statements;
}
else
{
 statements;
}

if (condition)
{
 statements;
}
else
{
 if (condition)
 {
  statements;
 }
 else
 {
  statements;
 }
}

Note: if statements always use braces {}. Avoid the following error-prone form:

if (condition) //AVOID! THIS OMITS THE BRACES {}!
   statement;

for Statements

A for statement should have the following form:

for (initialization; condition; update)
{
 statements;
}

An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:

for (initialization; condition; update)
{
}

This makes it easy to add code in the loop at a latter time.

When using the comma operator in the initialization or update clause of a for statement, avoid the complexity of using more than three variables. If needed, use separate statements before the for loop (for the initialization clause) or at the end of the loop (for the update clause).

while Statements

A while statement should have the following form:

while (condition)
{
 statements;
}

An empty while statement should have the following form:

while (condition)
{
}

This makes it easy to add code in the loop at a latter time.

do-while Statements

A do-while statement should have the following form:

do
{
 statements;
} while (condition);

switch Statements

A switch statement should have the following form:

switch (condition)
{
 case ABC:
    statements;
    /* falls through */
 case DEF:
    statements;
    break;
 case XYZ:
    statements;
    break;
 default:
    statements;
    break;
}

Every time a case falls through (doesn't include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ comment.

Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.

try-catch Statements

A try-catch statement should have the following format:

try
{
    statements;
}
catch (ExceptionClass e)
{
    statements;
}

A try-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.

try
{
    statements;
}
catch (ExceptionClass e)
{
    statements;
}
finally
{
    statements;
}

Programming Practices

Providing Access to Instance and Class Variables

Don't make any instance or class variable public without good reason. Often, instance variables don't need to be explicitly set or gotten. Often that happens as a side effect of method calls. It is preferred to set and get these types of variable by using a method. That way if logic needs to be applied now or in the future the public interface will not change.

One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.

Referring to Class Variables and Methods

Avoid using an object to access a class (static) variable or method. Use a class name instead. For example:

classMethod(); //OK
AClass.classMethod(); //OK

anObject.classMethod(); //AVOID!

Constants

Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values.

Variable Assignments

Avoid assigning several variables to the same value in a single statement. It is hard to read.

Example:
fooBar.fChar = barFoo.lchar = 'c'; // AVOID!

Do not use the assignment operator in a place where it can be easily confused with the equality operator.

Example:
if (c++ = d++) // AVOID! (Java disallows)
{
...
}

should be written as
if ((c++ = d++) != 0)
{
...
}

Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler.

Example:
d = (a = b + c) + r; // AVOID!

should be written as
a = b + c;
d = a + r;

Miscellaneous Practices

Parentheses

It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others. You shouldn't assume that other programmers know precedence as well as you do.

if (a == b && c == d) // AVOID!

if ((a == b) && (c == d)) // RIGHT

Returning Values

Try to make the structure of your program match the intent.

Example:
if (booleanExpression)
{
return true;
}
else
{
return false;
}

should instead be written as
return booleanExpression;

Similarly,
if (condition)
{
return x;
}
return y;

should be written as
return (condition ? x : y);

Expressions before "?" in the Conditional Operator

If an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesized.

Example:
(x >= 0) ? x : -x;

Special Comments

Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken.

Miscellaneous

Do not use syntax that utilizes some implied knowledge by the compiler. The source code statement should have the explicit language specification. The aids programmers who may not be familiar with the implied knowledge of a particular compiler of what the source statement actually is stating. The exception to this is the full class path declaration when referring to objects.

Portability Conventions

Refer to "Java in a Nutshell, 3rd Edition, David Flanagan, pg. 190-192)

Native methods

You can use any method, even native methods in the core Java API. However, portable code must not define its own native methods.

Runtime.exec() method

Spawning a process to execute a native system command is not portable unless the command is specified by the user either at runtime or in a configuration file.

System.getenv() method

This method is not portable.

Undocumented classes

These classes are not portable.

Java.awt.peer package

These are for use by the AWT implementors only, they are not portable.

Implementation-specific features

These features are not portable and are those features that are not defined by Sun.

Implementation-specific bugs

Don’t rely on the behavior of a method that has a bug. This may be different in another implementation or version.

Implementation-specific behavior

Don’t rely on behavior of a specific implementation of Java.

Standard extensions

Clearly document what extensions are required and exit the application cleanly if the extension is not installed on the target machine.

Complete programs

Supply all classes except core platform and standard extension classes of the application in a self-contained fashion.

Defining system classes

Do not define classes in the system or standard extension packages.

Hardcoded filenames

Do not hardcode filenames or directory paths.

Line separators

Do not hardcode "\n" or "\r". Use methods that imply these separators or use the line.separator system property.

Mixed event models

Do not use the Java 1.0 event model.

Documentation

Source Code Comments

Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are those found in C++, which are delimited by /*...*/, and //. Documentation comments (known as "doc comments") are Java-only, and are delimited by /**...*/. Doc comments can be extracted to HTML files using the javadoc tool.

Implementation comments are mean for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective to be read by developers who might not necessarily have the source code at hand.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.

Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves. The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer. Comments should NOT be enclosed in large boxes drawn with asterisks or other characters. Comments should never include special characters such as form-feed and backspace.

Implementation Comments

Programs can have four styles of implementation comments: block, single-line, trailing, and end-of-line.

Block Comments

Block comments are used to provide descriptions of files, methods, data structures and algorithms. Block comments may be used at the beginning of each file and before each method. They can also be used in other places, such as within methods. Block comments inside a function or method should be indented to the same level as the code they describe.

A block comment should be preceded by a blank line to set it apart from the rest of the code.

/*
 * Here is a block comment.
 */

Single Line Comments

Short comments can appear on a single line indented to the level of the code that follows. If a comment can't be written in a single line, it should follow the block comment format. A single-line comment should be preceded by a blank line. Here's an example of a single-line comment in Java code:

if (condition)
{
    /* Handle the condition. */
    ...
}

Trailing Comments

Very short comments can appear on the same line as the code they describe, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting.

Here's an example of a trailing comment in Java code:

if (a == 2)
{
    return TRUE;            /* special case */
}
else
{
    return isPrime(a);      /* works only for odd a */
}

End-Of-Line Comments

The // comment delimiter can comment out a complete line or only a partial line. It shouldn't be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code. Examples of all three styles follow:

if (foo > 1)
{
    // Do a double-flip.
    ...
}
else
{
    return false;          // Explain why here.
}
//if (bar > 1)
//{
//
//    // Do a triple-flip.
//    ...
//}
//else
//{
//    return false;
//}

Documentation Comments

These comments are associated with the javadoc tool and provide a means of documenting classes from the comments in the source code. Each doc comment is set inside the comment delimiters /**...*/, with one comment per class, interface, or member. This comment should appear just before the declaration:

/**
 * The Example class provides ...
 */
public class Example
{ ...

Notice that top-level classes and interfaces are not indented, while their members are. The first line of doc comment (/**) for classes and interfaces is not indented; subsequent doc comment lines each have 1 space of indentation (to vertically align the asterisks). Members, including constructors, have 4 spaces for the first doc comment line and 5 spaces thereafter. See the example.

If you need to give information about a class, interface, variable, or method that isn't appropriate for documentation, use an implementation block comment or single-line comment immediately after the declaration. For example, details about the implementation of a class should go in such an implementation block comment following the class statement, not in the class doc comment.

Doc comments should not be positioned inside a method or constructor definition block, because Java associates documentation comments with the first declaration after the comment.

Refer to "Java in a Nutshell, 3rd Edition, David Flanagan, pg. 192-199.

For further details, see "How to Write Doc Comments for Javadoc" which includes information on the doc comment tags (@return, @param, @see):
http://java.sun.com/products/jdk/javadoc/writingdoccomments.html

For further details about doc comments and javadoc, see the javadoc home page at:
http://java.sun.com/products/jdk/javadoc/

Source Code Format Example

The following example shows how to format a Java source file containing a single public class. Interfaces are formatted similarly.

/*
 * @(#)Blah.java
 *
 * Version Information:
 * Author              Version  Date
 * John Brown          1.0      19 Jan 2000
 *  original development
 * Fred Smith          1.1      28 Jun 2000
 *  added a new feature (describe feature)
 *
 * Copyright (c) 1994-1999 Sun Microsystems, Inc.
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * All rights reserved.
 *
 */

package java.blah;

import java.blah.blahdy.BlahBlah;

/**
 * Class description goes here.
 *
 * @version 	1.82 18 Mar 1999
 * @author 	Firstname Lastname
 */
public class Blah extends SomeClass
{
    /* A class implementation comment can go here. */

    /** classVar1 documentation comment */
    public static int classVar1;

    /** 
     * classVar2 documentation comment that happens to be
     * more than one line long
     */
    private static Object classVar2;

    /** instanceVar1 documentation comment */
    public Object instanceVar1;

    /** instanceVar2 documentation comment */
    protected int instanceVar2;

    /** instanceVar3 documentation comment */
    private Object[] instanceVar3;

    /** 
     * ...constructor Blah documentation comment...
     */
    public Blah()
    {
     // ...implementation goes here...
    }

    /**
     * ...method doSomething documentation comment...
     */
    public void doSomething()
    {
     // ...implementation goes here... 
    }

    /**
     * ...method doSomethingElse documentation comment...
     * @param someParam description
     */
    public void doSomethingElse(Object someParam)
    {
     // ...implementation goes here... 
    }

} //end class Blah

 

[Index]